use ggez::{
    graphics::{self, Canvas, Color, DrawParam, Image, PxScale, Text, TextFragment},
    Context,
};
use glam::Vec2;
use hecs::{Entity, World};
// ANCHOR: use_itertools
use itertools::Itertools;
// ANCHOR_END: use_itertools

use std::collections::HashMap;
use std::time::Duration;

use crate::components::*;
use crate::constants::*;

// ANCHOR: run_rendering
pub fn run_rendering(world: &World, context: &mut Context) {
    // Clearing the screen (this gives us the background colour)
    let mut canvas =
        graphics::Canvas::from_frame(context, graphics::Color::from([0.95, 0.95, 0.95, 1.0]));
    // ANCHOR_END: run_rendering

    // Get time
    let mut query = world.query::<&Time>();
    let time = query.iter().next().unwrap().1;

    // Get all the renderables with their positions and sort by the position z
    // This will allow us to have entities layered visually.
    let mut query = world.query::<(&Position, &Renderable)>();
    let mut rendering_data: Vec<(Entity, (&Position, &Renderable))> = query.into_iter().collect();
    rendering_data.sort_by_key(|&k| k.1 .0.z);

    // ANCHOR: rendering_batches
    let mut rendering_batches: HashMap<u8, HashMap<String, Vec<DrawParam>>> = HashMap::new();

    // Iterate each of the renderables, determine which image path should be rendered
    // at which drawparams, and then add that to the rendering_batches.
    for (_, (position, renderable)) in rendering_data.iter() {
        // 使用修改后的get_image函数
        let image_path = get_image(world, renderable, time.delta);
        let x = position.x as f32 * TILE_WIDTH;
        let y = position.y as f32 * TILE_WIDTH;
        let z = position.z;

        let draw_param = DrawParam::new().dest(Vec2::new(x, y));
        rendering_batches
            .entry(z)
            .or_default()
            .entry(image_path)
            .or_default()
            .push(draw_param);
    }
    // ANCHOR_END: rendering_batches

    // ANCHOR: rendering_batches_2
    // Iterate spritebatches ordered by z and actually render each of them
    for (_z, group) in rendering_batches
        .iter()
        .sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
    {
        for (image_path, draw_params) in group {
            let image = Image::from_path(context, image_path).unwrap();
            let mut mesh_batch = graphics::InstanceArray::new(context, Some(image));

            for draw_param in draw_params.iter() {
                mesh_batch.push(*draw_param);
            }

            canvas.draw(&mesh_batch, graphics::DrawParam::new());
        }
    }
    // ANCHOR_END: rendering_batches_2

    // Render any text
    let mut query = world.query::<&Gameplay>();
    let gameplay = query.iter().next().unwrap().1;
    let right = 800.0 - 150.0; // 右上角起始x坐标
    draw_text(&mut canvas, &format!("State: {}", gameplay.state), right, 20.0);
    draw_text(&mut canvas, &format!("Moves: {}/{}", gameplay.moves_count, gameplay.max_moves), right, 40.0);
    let fps = format!("FPS: {:.0}", context.time.fps());
    draw_text(&mut canvas, &fps, right, 60.0);
    // ANCHOR_END: render_fps

    // ANCHOR: run_rendering_end
    // Finally, present the canvas, this will actually display everything
    // on the screen.
    canvas.finish(context).expect("expected to present");
}
// ANCHOR_END: run_rendering_end

pub fn draw_text(canvas: &mut Canvas, text_string: &str, x: f32, y: f32) {
    let text = Text::new(TextFragment {
        text: text_string.to_string(),
        color: Some(Color::new(0.0, 0.0, 0.0, 1.0)),
        scale: Some(PxScale::from(20.0)),
        ..Default::default()
    });

    canvas.draw(&text, Vec2::new(x, y));
}

// ANCHOR: get_image
pub fn get_image(world: &World, renderable: &Renderable, delta: Duration) -> String {
    let path_index = match renderable.kind() {
        RenderableKind::Static => 0,
        RenderableKind::Animated => {
            ((delta.as_millis() % 1000) / 250) as usize
        }
    };

    // 直接返回路径，删除重复的代码
    renderable.path(path_index)
}
// ANCHOR_END: get_image

//新增菜单渲染

pub fn run_menu_rendering(_world: &World, context: &mut Context, selected: usize) {
    let mut canvas = graphics::Canvas::from_frame(context, graphics::Color::from([0.1, 0.1, 0.1, 1.0]));
    
    // Draw title
    let title_text = Text::new(TextFragment {
        text: "Sokoban Game".to_string(),
        color: Some(Color::new(1.0, 1.0, 1.0, 1.0)),
        scale: Some(PxScale::from(30.0)),
        ..Default::default()
    });
    canvas.draw(&title_text, Vec2::new(300.0, 150.0));
    
    // Draw menu items - 只保留 Start Game
    let menu_items = ["Start Game"]; // 删除 "Style"
    for (i, &item) in menu_items.iter().enumerate() {
        let color = if i == selected {
            Color::new(1.0, 1.0, 0.0, 1.0) // 选中为黄色
        } else {
            Color::new(1.0, 1.0, 1.0, 1.0) // 未选中为白色
        };
        
        let text = Text::new(TextFragment {
            text: item.to_string(),
            color: Some(color),
            scale: Some(PxScale::from(20.0)),
            ..Default::default()
        });
        canvas.draw(&text, Vec2::new(300.0, 250.0 + (i as f32 * 40.0)));
    }
    
    // Draw instructions
    let instruction_text = Text::new(TextFragment {
        text: "Press Enter to Start".to_string(), // 修改提示文字
        color: Some(Color::new(0.7, 0.7, 0.7, 1.0)),
        scale: Some(PxScale::from(15.0)),
        ..Default::default()
    });
    canvas.draw(&instruction_text, Vec2::new(250.0, 400.0));
    
    canvas.finish(context).expect("expected to present");
}

pub fn run_win_menu_rendering(_world: &World, context: &mut Context) {
    let mut canvas = graphics::Canvas::from_frame(context, graphics::Color::from([0.0, 0.5, 0.0, 0.8]));
    
    let title_text = Text::new(TextFragment {
        text: "Congratulations!".to_string(),
        color: Some(Color::new(1.0, 1.0, 0.0, 1.0)),
        scale: Some(PxScale::from(30.0)),
        ..Default::default()
    });
    canvas.draw(&title_text, Vec2::new(300.0, 200.0));
    
    let instruction_text = Text::new(TextFragment {
        text: "Press Enter to Return to Menu".to_string(), 
        color: Some(Color::new(1.0, 1.0, 1.0, 1.0)),
        scale: Some(PxScale::from(20.0)),
        ..Default::default()
    });
    canvas.draw(&instruction_text, Vec2::new(300.0, 300.0));
    
    canvas.finish(context).expect("expected to present");
}

//新增关卡选择页面渲染
pub fn run_level_select_rendering(_world: &World, context: &mut Context, selected: usize) {
    let mut canvas = graphics::Canvas::from_frame(context, graphics::Color::from([0.15, 0.15, 0.15, 1.0]));

    // 标题
    let title_text = Text::new(TextFragment {
        text: "Select Level".to_string(),
        color: Some(Color::new(1.0, 1.0, 1.0, 1.0)),
        scale: Some(PxScale::from(30.0)),
        ..Default::default()
    });
    canvas.draw(&title_text, Vec2::new(300.0, 150.0));

    // 关卡名称
    let levels = [
        "Level 1: Basic",
        "Level 2: Maze",
        "Level 3: Mirror"
    ];
    for (i, &name) in levels.iter().enumerate() {
        let color = if i == selected {
            Color::new(1.0, 1.0, 0.0, 1.0) // 选中为黄色
        } else {
            Color::new(1.0, 1.0, 1.0, 1.0) // 未选中为白色
        };
        let text = Text::new(TextFragment {
            text: name.to_string(),
            color: Some(color),
            scale: Some(PxScale::from(24.0)),
            ..Default::default()
        });
        canvas.draw(&text, Vec2::new(320.0, 220.0 + (i as f32) * 40.0));
    }

    // 操作提示
    let instruction_text = Text::new(TextFragment {
        text: "Use Up/Down to select, Enter to confirm".to_string(),
        color: Some(Color::new(0.8, 0.8, 0.8, 1.0)),
        scale: Some(PxScale::from(16.0)),
        ..Default::default()
    });
    canvas.draw(&instruction_text, Vec2::new(250.0, 350.0));

    canvas.finish(context).expect("expected to present");
}

pub fn run_return_menu_rendering(_world: &World, context: &mut Context) {
    let mut canvas = graphics::Canvas::from_frame(context, graphics::Color::from([0.5, 0.0, 0.0, 0.8]));  // 红色背景
    
    let title_text = Text::new(TextFragment {
        text: "Return to Menu".to_string(),
        color: Some(Color::new(1.0, 1.0, 0.0, 1.0)),
        scale: Some(PxScale::from(30.0)),
        ..Default::default()
    });
    canvas.draw(&title_text, Vec2::new(300.0, 200.0));
    
    let instruction_text = Text::new(TextFragment {
        text: "Press Enter to confirm".to_string(),
        color: Some(Color::new(1.0, 1.0, 1.0, 1.0)),
        scale: Some(PxScale::from(20.0)),
        ..Default::default()
    });
    canvas.draw(&instruction_text, Vec2::new(300.0, 300.0));
    
    canvas.finish(context).expect("expected to present");
}

pub fn run_failed_menu_rendering(_world: &World, context: &mut Context) {
    let mut canvas = graphics::Canvas::from_frame(context, graphics::Color::from([0.5, 0.0, 0.0, 0.8])); // 红色背景
    
    let title_text = Text::new(TextFragment {
        text: "Game Over!".to_string(),
        color: Some(Color::new(1.0, 0.0, 0.0, 1.0)), // 红色文字
        scale: Some(PxScale::from(30.0)),
        ..Default::default()
    });
    canvas.draw(&title_text, Vec2::new(300.0, 200.0));
    
    let instruction_text = Text::new(TextFragment {
        text: "Press Enter to Return to Menu".to_string(),
        color: Some(Color::new(1.0, 1.0, 1.0, 1.0)),
        scale: Some(PxScale::from(20.0)),
        ..Default::default()
    });
    canvas.draw(&instruction_text, Vec2::new(300.0, 300.0));
    
    canvas.finish(context).expect("expected to present");
}

pub fn run_difficulty_select_rendering(_world: &World, context: &mut Context, selected: usize) {
    let mut canvas = graphics::Canvas::from_frame(context, graphics::Color::from([0.15, 0.15, 0.15, 1.0]));

    // 标题
    let title_text = Text::new(TextFragment {
        text: "Select Difficulty".to_string(),
        color: Some(Color::new(1.0, 1.0, 1.0, 1.0)),
        scale: Some(PxScale::from(30.0)),
        ..Default::default()
    });
    canvas.draw(&title_text, Vec2::new(300.0, 150.0));

    // 难度选项
    let difficulties = [
        "Easy",
        "Hard"
    ];
    for (i, &name) in difficulties.iter().enumerate() {
        let color = if i == selected {
            Color::new(1.0, 1.0, 0.0, 1.0) // 选中为黄色
        } else {
            Color::new(1.0, 1.0, 1.0, 1.0) // 未选中为白色
        };
        let text = Text::new(TextFragment {
            text: name.to_string(),
            color: Some(color),
            scale: Some(PxScale::from(24.0)),
            ..Default::default()
        });
        canvas.draw(&text, Vec2::new(320.0, 220.0 + (i as f32) * 40.0));
    }

    // 操作提示
    let instruction_text = Text::new(TextFragment {
        text: "Use Up/Down to select, Enter to confirm".to_string(),
        color: Some(Color::new(0.8, 0.8, 0.8, 1.0)),
        scale: Some(PxScale::from(16.0)),
        ..Default::default()
    });
    canvas.draw(&instruction_text, Vec2::new(250.0, 350.0));

    canvas.finish(context).expect("expected to present");
}

